package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// RelationshipStatHandler 恋爱统计处理器
type RelationshipStatHandler struct {
	client *ent.Client
}

// NewRelationshipStatHandler 创建恋爱统计处理器
func NewRelationshipStatHandler(client *ent.Client) *RelationshipStatHandler {
	return &RelationshipStatHandler{client: client}
}

// CreateRelationshipStatRequest 创建恋爱统计请求
type CreateRelationshipStatRequest struct {
	TogetherSince  string `json:"together_since"`   // 格式: 2006-01-02
	FirstMeetDate  string `json:"first_meet_date"`  // 格式: 2006-01-02
	MeetCount      int32  `json:"meet_count"`
}

// UpdateRelationshipStatRequest 更新恋爱统计请求
type UpdateRelationshipStatRequest struct {
	TogetherSince  string `json:"together_since"`
	FirstMeetDate  string `json:"first_meet_date"`
	MeetCount      int32  `json:"meet_count"`
}

// GetRelationshipStats 获取所有恋爱统计（通常只有一条记录）
func (h *RelationshipStatHandler) GetRelationshipStats(c *fiber.Ctx) error {
	ctx := context.Background()
	stats, err := h.client.RelationshipStat.Query().All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取恋爱统计失败")
	}

	return models.Success(c, stats)
}

// GetRelationshipStat 获取单个恋爱统计
func (h *RelationshipStatHandler) GetRelationshipStat(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的统计ID")
	}

	stat, err := h.client.RelationshipStat.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "统计记录不存在")
		}
		return models.InternalServerError(c, "获取统计记录失败")
	}

	return models.Success(c, stat)
}

// CreateRelationshipStat 创建恋爱统计
func (h *RelationshipStatHandler) CreateRelationshipStat(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateRelationshipStatRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.TogetherSince == "" {
		return models.BadRequest(c, "在一起日期不能为空")
	}

	// 解析在一起日期
	togetherSince, err := time.Parse("2006-01-02", req.TogetherSince)
	if err != nil {
		return models.BadRequest(c, "在一起日期格式错误，应为: 2006-01-02")
	}

	builder := h.client.RelationshipStat.
		Create().
		SetTogetherSince(togetherSince).
		SetMeetCount(req.MeetCount)

	// 第一次见面日期是可选的
	if req.FirstMeetDate != "" {
		firstMeetDate, err := time.Parse("2006-01-02", req.FirstMeetDate)
		if err != nil {
			return models.BadRequest(c, "第一次见面日期格式错误")
		}
		builder.SetFirstMeetDate(firstMeetDate)
	}

	stat, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建恋爱统计失败")
	}

	return models.SuccessWithMessage(c, "创建成功", stat)
}

// UpdateRelationshipStat 更新恋爱统计
func (h *RelationshipStatHandler) UpdateRelationshipStat(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的统计ID")
	}

	var req UpdateRelationshipStatRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.RelationshipStat.UpdateOneID(id)

	if req.TogetherSince != "" {
		togetherSince, err := time.Parse("2006-01-02", req.TogetherSince)
		if err != nil {
			return models.BadRequest(c, "在一起日期格式错误")
		}
		builder.SetTogetherSince(togetherSince)
	}

	if req.FirstMeetDate != "" {
		firstMeetDate, err := time.Parse("2006-01-02", req.FirstMeetDate)
		if err != nil {
			return models.BadRequest(c, "第一次见面日期格式错误")
		}
		builder.SetFirstMeetDate(firstMeetDate)
	}

	if req.MeetCount >= 0 {
		builder.SetMeetCount(req.MeetCount)
	}

	stat, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "统计记录不存在")
		}
		return models.InternalServerError(c, "更新统计记录失败")
	}

	return models.SuccessWithMessage(c, "更新成功", stat)
}

// DeleteRelationshipStat 删除恋爱统计
func (h *RelationshipStatHandler) DeleteRelationshipStat(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的统计ID")
	}

	err = h.client.RelationshipStat.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "统计记录不存在")
		}
		return models.InternalServerError(c, "删除统计记录失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}
